<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="任务单号" prop="taskNumber">
        <el-input
          v-model="queryParams.taskNumber"
          placeholder="请输入任务单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="订单类型" prop="dictOrderType">
        <el-select
          v-model="queryParams.dictOrderType"
          placeholder="请选择订单类型"
          clearable
          class="!w-220px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MARKET_ORDER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户代码" prop="customerCode">
        <el-input
          v-model="queryParams.customerCode"
          placeholder="请输入客户代码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品编号" prop="productNumber">
        <el-input
          v-model="queryParams.productNumber"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="部件类型" prop="partType">
        <el-input
          v-model="queryParams.partType"
          placeholder="请输入部件名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="设计员" prop="designerPersonName">
        <el-input
          v-model="queryParams.designerPersonName"
          placeholder="请输入设计员"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div style="width: 100%; height: 50px; display: flex; justify-content: space-between">
      <div>
        <el-button
          type="primary"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['technology:drawing-task:export']"
        >
          数据导出
        </el-button>
      </div>
      <el-button type="primary" @click="openTableTitleSet"> 表头设置 </el-button>
    </div>
    <Table
      :columns="tableTitleList"
      :selection="tableObject.tableList.length ? true : false"
      @register="tableoperation"
      @update:currentPage="getTableData"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.pageNo"
      :tableHeight="tableHeight"
    >
      <template #action="{ row }">
        <!-- 
          任务类型：dictTaskType 10:正常/20:变更 
          数据状态：dictStatus 30：待制图 50:制图中 60:任务暂停
        -->
        <el-button
          link
          type="primary"
          @click="editDataType(row, 'begin')"
          v-hasPermi="['technology:drawing-task:begin']"
          v-if="[30, 60].includes(row.dictStatus)"
        >
          开始
        </el-button>
        <el-button
          link
          type="primary"
          @click="editDataType(row, 'suspend')"
          v-hasPermi="['technology:drawing-task:suspend']"
          v-if="[50].includes(row.dictStatus)"
        >
          暂停
        </el-button>
        <el-button
          link
          type="primary"
          @click="editFinished(row)"
          v-hasPermi="['technology:drawing-task:finished']"
          v-if="[50, 60].includes(row.dictStatus)"
        >
          完工
        </el-button>

        <el-button
          link
          type="primary"
          @click="openForm('edit', row.id)"
          v-hasPermi="['technology:drawing-task:update']"
          v-if="[50, 60].includes(row.dictStatus)"
        >
          编辑
        </el-button>
        <el-button
          link
          type="primary"
          @click="openForm('look', row.id)"
          v-hasPermi="['technology:drawing-task:view']"
        >
          查看
        </el-button>
      </template>
    </Table>
  </ContentWrap>
  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
  <!-- 表头设置 -->
  <TableWidthSet ref="tableTitleSet" @refresh="getLabelAll" />
</template>

<script setup lang="ts" name="DrawingTask">
   import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
   import download from '@/utils/download'
   import type { CrudSchema } from '@/hooks/web/useCrudSchemas'
   import * as DrawingTaskApi from '@/api/technology/drawingTask'
   let tableTitleList = reactive<CrudSchema[]>([]) // 表头的数据
   const message = useMessage() // 消息弹窗
   const { t } = useI18n() // 国际化

   const queryParams = reactive({
     pageNo: 1,
     pageSize: 10,
     taskNumber: null,
     orderNumber: null,
     dictOrderType: null,
     customerName: null,
     customerCode: null,
     productNumber: null,
     productName: null,
     partType: null,
     designerPersonName: null
   })
   const queryFormRef = ref() // 搜索的表单
   const exportLoading = ref(false) // 导出的加载中
   // tableObject：表格的属性对象，可获得分页大小、条数等属性
   // tableMethods：表格的操作对象，可进行获得分页、删除记录等操作getUserLabelPage
   // 详细可见：https://doc.iocoder.cn/vue3/crud-schema/
   const { tableObject, tableMethods } = useTable({
     getListApi: DrawingTaskApi.getDrawingTaskPage, // 分页接口
     defaultParams: queryParams
   })

   /**表头数据 */
   const getLabelAll = async () => {
     try {
       const data = await DrawingTaskApi.getDrawingTaskPage(queryParams)
       const { allSchemas } = useCrudSchemas(data.labels)
       allSchemas.tableColumns.push({
         label: '操作',
         field: 'action',
         isDetail: false,
         width: 200
       })
       tableTitleList = allSchemas.tableColumns
       /**表头修改需要刷新表格 */
       getList()
     } finally {
     }
   }
   /** 查询列表 */
   const getTableData = (val) => {
     tableObject.currentPage = val

     getList()
   }
   // 获得表格的各种操作
   const { getList } = tableMethods

   /**表头内部方法 */
   const usTableoperation = ref()
   const tableoperation = (parent: any) => {
     usTableoperation.value = parent
   }
   /** 搜索按钮操作 */
   const handleQuery = () => {
     queryParams.pageNo = 1
     getList()
   }

   /** 重置按钮操作 */
   const resetQuery = () => {
     queryFormRef.value.resetFields()
     tableObject.params = queryParams
     getList()
   }
   /** 修改 */
   const { push } = useRouter() // 路由
   const openForm = (type: string, id: number) => {
     console.log(id)
     push({
       path: '/technology/technology/drawingProduction/DrawingTaskForm',
       query: {
         id,
         type
       }
     })
   }

   /**完工,跳转设计完工单新增 */
   const editFinished = async (data: object) => {
     console.log(data)
     push({
       path: '/technology/technology/drawingProduction/designCompleteTicketDetail',
       query: {
         carryingParametersId: data.id,
         type: 'create'
       }
     })
   }

   /**暂停/开始
    * 任务类型：dictTaskType 10:正常/20:变更
    *  数据状态：dictStatus 40：未开始 50:制图中 60:任务暂停
    * optionFlag 1:开始 2：暂停
    */
   const editDataType = async (res: object, type: string) => {
     //点击暂停按钮参数
     const data = {
       optionFlag: 2,
       partType: res.partType,
       id: res.id
     }
     //点击开始按钮
     if (type == 'begin') {
       //如果是变更就去设计变更单
       if (res.dictTaskType == 20) {
         const {
           id,
           taskNumber,
           productNumber,
           productName,
           partType,
           customerCode,
           customerName,
           productType,
           productStandard
         } = res
          push({
            path: '/technology/technology/drawingProduction/designAlertTicketForm',
            query: {
              type: 'jump',
              taskId:id,
              taskNumber,
              productNumber,
              productName,
              partType,
              customerCode,
              customerName,
              productType,
              productStandard
            }
          })
         return
       } else {
         data.optionFlag = 1
       }
     }
     await DrawingTaskApi.operateDrawingTask(data)
     message.success(t('common.updateSuccess'))
     // 刷新列表
     await getList()
   }

   /** 导出按钮操作 */
   const exportRef = ref()
   const handleExport = () => {
     exportRef.value.open()
   }
   // 导出
   const downloadFun = async () => {
     const val = exportRef.value.params
     let params = {
       fileName: val.name,
       ids: ''
     }
     if (val.range === 'all') {
       params.ids = ''
     } else {
       params.ids = usTableoperation.value.selections.map((item) => item.id)
     }
     console.log(params)
     DrawingTaskApi.exportDrawingTask(params).then((res) => {
       download.excel(res, val.name)
       clearSelectData()
     })
   }

   //清空多选
   const clearSelectData = () => {
     usTableoperation.value.selections = []
     usTableoperation.value.clearTableSelect()
   }

   /**打开表格表头设置**/
   const tableTitleSet = ref()
   const openTableTitleSet = () => {
     let code = 'drawingTask'
     console.log(tableTitleList)
     tableTitleSet.value.open(tableTitleList, code)
   }

   /** 初始化 **/
   const tableHeight = ref(0)
   //132：表格内除表格以外的高度，127 顶部固定高度 + copyright高度
   onMounted(async () => {
     const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
     tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 127
     await getLabelAll()
     getList()
   })
</script>
